/*global $ jQuery */
jQuery.extend({
    createHistogram: (function() {
        var histogramPrototype = {
        // k: null, //number of buckets
        // min: null, //minimum expected value, okay for x to exceed min
        // or max, the index goes negative or beyond k. this is okay
        // because the purpose is to generate histogramPoints
        // max: null, //maximum expected value
        // buckets: {}, //declaring as object allows negative array
        // accesses, buckets[m] is number of points in bucket m
        // histogramPoints: [], //points to plot on xy graph, y
        // determined by size of bucket
        calculateBucket: function(x) {
            // To guard against a case where the entire set of
            // bootstrapped points yields the same value, thus only one
            // usable bucket
            if (this.max - this.min === 0) {
                return 0;
            }
            return Math.floor((x - this.min) / (this.max - this.min) * this.k);
        },
        addPoints: function(data, type) {
            if (this.k === null || this.min === null || this.max === null) {
                throw "min, max, or k not set";
            }

            var x, y, point, m, i, h;
            h = (this.max - this.min) / this.k;
            for (i = 0; i < data.length; i += 1) {
                x = data[i][this.type];
                m = this.calculateBucket(x);
                y = this.buckets[m] = (this.buckets[m] + 1 || 1);
                point = [ this.min + m * h, y, data[i].generatedFrom, x ];
                if (this.options.raggedPlot) {
                    point[0] = x;
                }
                this.histogramPoints.push(point);
            }
        },
        clear: function() {
            this.histogramPoints = [];
            this.buckets = {};
        }
        };
        return function(options) {
            //Prototypal inheritance
            var F = function() {
            };
            F.prototype = histogramPrototype;
            options = options || {};
            F.prototype.options = options;
            return new F();
        };
    }())
});